package com.apobates.jforum2.troll.threads.biz.impl;

import com.apobates.jforum2.troll.threads.biz.TopicTagService;
import com.apobates.jforum2.troll.threads.biz.dao.TopicTagDao;
import com.apobates.jforum2.troll.threads.entity.TopicTag;
import com.apobates.jforum2.troll.utils.core.api.ActionEventCulpritor;
import com.apobates.jforum2.troll.utils.persistence.Page;
import com.apobates.jforum2.troll.utils.persistence.Pageable;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author xiaofanku
 * @since 20200513
 */
@Service
public class TopicTagServiceImpl implements TopicTagService{
    @Autowired
    private TopicTagDao topicTagDao;
    private final static Logger logger = LoggerFactory.getLogger(TopicTagServiceImpl.class);

    //@Cacheable(value="topicCache", key="'tag_'+#topicId")
    @Override
    public List<TopicTag> getAllBy(long topicId) {
        return topicTagDao.findAllByTopic(topicId);
    }
    
    //@CacheEvict(value="topicCache", key="'tag_'+#topicId")
    @Transactional
    @GlobalTransactional
    @Override
    public Optional<Boolean> deleteForTopic(long topicId, long tagId, ActionEventCulpritor culpritor) {
        return topicTagDao.remove(tagId, topicId);
    }
    
    //@CacheEvict(value="topicCache", key="'tag_'+#topicId")
    @Override
    public Optional<Boolean> addForTopic(long topicId, Map<String, Integer> tagData, ActionEventCulpritor culpritor) {
        int affect = topicTagDao.batchSave(topicId, tagData);
        return affect == tagData.size() ? Optional.of(true) : Optional.empty();
    }
    
    //@CacheEvict(value="topicCache", key="'tag_'+#topicId")
    @Transactional
    @GlobalTransactional
    @Override
    public long create(long topicId, String names, int rates, ActionEventCulpritor culpritor) {
        TopicTag tt = new TopicTag(names, rates, topicId);
        try{
            topicTagDao.save(tt);
            if (tt.getId() > 0) {
                return tt.getId();
            }
        }catch(Exception e){
            if(logger.isDebugEnabled()){
                logger.debug("新增标签操作失败", e);
            }
        }
        return 0L;
    }
    @Override
    public Page<TopicTag> getAll(Pageable pageable) {
        return topicTagDao.findAll(pageable);
    }
    
    @Override
    public Map<String, Long> groupTagForNames(int size) {
        return topicTagDao.groupTagForNames(size);
    }
}